<template>
  <div>
    <a-card>
      <a-row :gutter="20">
        <a-col :span="4">
          <a-button type="primary" @click="addCategory">新增分类</a-button>
        </a-col>
      </a-row>
      <a-table
        :rowKey="(record) => record.id"
        :columns="columns"
        :pagination="paginationOption"
        :dataSource="CategoryList"
        bordered
      >
        <template slot="action" slot-scope="data">
          <div class="actionSlot">
            <a-button
              type="primary"
              icon="edit"
              style="margin-right: 15px"
              @click="editCategory(data.id)"
              >编辑</a-button
            >
            <a-button
              type="danger"
              icon="delete"
              style="margin-right: 15px"
              @click="deleteCategory(data.id)"
              >删除</a-button
            >
          </div>
        </template>
      </a-table>
    </a-card>
    <!-- 新增分类 -->
    <a-modal
      title="新增分类"
      :visible="addCategoryVisible"
      @ok="addCategoryOk"
      @cancel="addCategoryCancel"
      closable
      destroyOnClose
    >
      <a-form-model
        :model="newCategoryInfo"
        :rules="CategoryRules"
        ref="addCategoryRef"
      >
        <a-form-model-item label="分类名" prop="name">
          <a-input v-model="newCategoryInfo.name"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
    <!-- 编辑分类区 -->
    <a-modal
      title="编辑分类"
      :visible="editCategoryVisiable"
      @ok="editCategoryOk"
      @cancel="editCategoryCancel"
      closable
      destroyOnClose
    >
      <a-form-model
        :model="editCategoryInfo"
        :rules="CategoryRules"
        ref="editCategoryRef"
      >
        <a-form-model-item label="分类名" prop="name">
          <a-input v-model="editCategoryInfo.name"></a-input>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
export default {
  data() {
    return {
      CategoryList: [],
      columns: [
        {
          title: "ID",
          dataIndex: "id",
          width: "5%",
          key: "id",
          align: "center",
        },
        {
          title: "分类名",
          dataIndex: "name",
          width: "20%",
          key: "name",
          align: "center",
        },

        {
          title: "操作",
          width: "15%",
          key: "action",
          scopedSlots: { customRender: "action" },
          align: "center",
        },
      ],
      paginationOption: {
        pageSizeOptions: ["2", "5", "10", "15"],
        defaultCurrent: 1,
        defaultPageSize: 2,
        total: 0,
        showSizeChanger: true,
        showTotal: (total) => `共${total}条`,
        onChange: (current, pageSize) => {
          this.paginationOption.defaultCurrent = current;
          this.getCategoryList();
        },
        onShowSizeChange: (current, size) => {
          this.paginationOption.defaultCurrent = 1;
          this.paginationOption.defaultPageSize = size;
          this.getCategoryList();
        },
      },
      queryParam: {
        pageSize: 2,
        pageNum: 1,
      },
      addCategoryVisible: false,
      editCategoryVisiable: false,
      newCategoryInfo: {
        id: 0,
        name: "",
      },
      addSwitch: false,
      editSwitch: false,
      editCategoryInfo: {
        id: 0,
        name: "",
      },
      CategoryRules: {
        name: [{ required: true, message: "请输入分类名" }],
      },
    };
  },
  created() {
    this.getCategoryList();
  },
  methods: {
    // 分页获取分类信息
    async getCategoryList() {
      let that = this;
      const { data: res } = await this.$http.get("/categories", {
        params: {
          pageNum: that.paginationOption.defaultCurrent,
          pageSize: that.paginationOption.defaultPageSize,
        },
      });

      if (res.status != 200) return this.$message.error(res.msg);
      this.CategoryList = res.data;
      this.paginationOption.total = res.total;
    },
    // 删除分类
    deleteCategory(id) {
      let that = this;
      this.$confirm({
        title: "确定要删除该分类吗?",
        content: "一旦删除无法恢复",
        okText: "Yes",
        okType: "danger",
        cancelText: "No",
        async onOk() {
          const { data: res } = await that.$http.delete(`/category/${id}`);
          if (res.status != 200) return that.$message.error(res.msg);
          that.$message.success("删除成功");
          that.getCategoryList();
        },
        onCancel() {
          that.$message.info("已取消");
        },
      });
    },
    // 新增分类
    addCategory() {
      this.addCategoryVisible = true;
    },
    // 新增分类同意回调
    addCategoryOk() {
      // 先校验新增分类信息
      this.$refs.addCategoryRef.validate(async (valid) => {
        if (!valid) return this.$message.error("参数不符合输入，请重新输入");
        // 发送新增分类请求
        const { data: res } = await this.$http.post("/category/add", {
          name: this.newCategoryInfo.name,
        });
        if (res.status != 200) return this.$message.error(res.msg);
        this.$message.success("添加分类成功");
        // 重置
        this.addCategoryVisible = false;
        this.$refs.addCategoryRef.resetFields();
        await this.getCategoryList();
      });
    },
    // 新增分类取消回调
    addCategoryCancel() {
      this.addCategoryVisible = false;
      this.$refs.addCategoryRef.resetFields();
      this.$message.info("新增取消");
    },

    // 编辑分类
    async editCategory(id) {
      // 获取分类信息返回到编辑栏上
      this.editCategoryInfo.id = id;
      const { data: res } = await this.$http.get(`/category/${id}`);
      if (res.status != 200) return this.$message.error("分类信息获取失败");
      this.editCategoryInfo.name = res.data.name;
      // 显示编辑栏
      this.editCategoryVisiable = true;
    },
    // 编辑分类同意回调
    editCategoryOk() {
      this.$refs.editCategoryRef.validate(async (valid) => {
        if (!valid) return this.$message.error("参数不符合输入，请重新输入");
        // 发送新增分类请求
        const { data: res } = await this.$http.put(
          `/category/${this.editCategoryInfo.id}`,
          {
            name: this.editCategoryInfo.name,
            role: this.editCategoryInfo.role,
          }
        );
        if (res.status != 200) return this.$message.error(res.msg);
        this.$message.success("更新分类成功");
        // 重置
        this.editCategoryVisiable = false;
        this.$refs.editCategoryRef.resetFields();
        this.getCategoryList();
      });
    },
    // 编辑分类取消回调
    editCategoryCancel() {
      this.editCategoryVisiable = false;
      this.$message.info("编辑取消");
    },
  },
};
</script>

<style lang="scss" scoped>
.actionSlot {
  display: flex;
  justify-content: center;
}
</style>